package com.icesoft.core.web.helper.http;

import com.fasterxml.jackson.core.type.TypeReference;
import com.icesoft.core.common.exception.CheckException;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.util.JsonUtil;
import com.icesoft.core.web.suppose.safehttp.service.ICryptoService;
import lombok.Getter;

public class SafeRequestResult {
    @Getter
    private String json;

    public <T> Resp<T> toResp(TypeReference<Resp<T>> responseType) {
        return JsonUtil.toObject(json, responseType);
    }

    public SafeRequestResult(String encryptData, String sign, ICryptoService cryptoService) {
        this.json = decryptJson(encryptData, sign, cryptoService);
    }

    public static String decryptJson(String json, String sign, ICryptoService cryptoService) {
        Resp<String> resp = JsonUtil.toObject(json, new TypeReference<Resp<String>>() {
        });
        try {
            resp.setData(cryptoService.symmetricDecrypt(sign, resp.getData()));
        } catch (IllegalArgumentException e) {
            throw new CheckException("解密出错:" + resp.getData());
        }
        StringBuilder sb = new StringBuilder("{");
        if (resp.getMsg() != null) {
            sb.append("\"msg\":\"").append(resp.getMsg()).append("\",");
        }
        sb.append("\"code\":").append(resp.getCode()).append(",\"data\":").append(resp.getData()).append("}");
        json = sb.toString();
        return json;

    }

}
